package com.haojiang.mh.ui.fragment

import android.view.View
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.Util
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.activity.ChooseWebServiceActivity
import com.haojiang.mh.ui.activity.DeviceListActivity
import com.haojiang.mh.ui.activity.UpdateFirmwareActivity
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.ui.base.LazyLoadBaseFragment
import com.haojiang.mh.utils.SpUtil
import com.haojiang.mh.widget.CommonDialog
import com.haojiang.mh.widget.CustomToggle
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import kotlinx.android.synthetic.main.fragment_three.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 设置
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
class ThreeFragment : LazyLoadBaseFragment() {


    private val mIPermissionCallback = IPermissionCallback {
        context.redirectNoParam(DeviceListActivity::class.java)
    }


    override fun getLayoutId() = R.layout.fragment_three

    override fun initView() {
    }

    override fun onFragmentFirstVisible() {
        ct_single_double.setOnCheckedChange(checkListener)
        ct_snoring_intervene.setOnCheckedChange(checkListener)
        ct_left_intervene.setOnCheckedChange(checkListener)
        ct_right_intervene.setOnCheckedChange(checkListener)
        ll_device_bt.setOnClickListener {
            if (SpUtil[Const.DEVICE_MAC, ""].isEmpty()) {
                if (!Util.checkBleStatus(context)) return@setOnClickListener
                //申请权限
                PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
                PermissionManager.getInstance().requestPermission(
                    context,
                    BleUtil.permissionArr
                )
            } else {
                showDeleteDialog()
            }
        }
        bt_update.setOnClickListener {
            context.redirectNoParam(UpdateFirmwareActivity::class.java)
        }
        bt_cancel.setOnClickListener {
            BleHandle.instance.isCancelUpdate = true
            refreshView()
        }
        rl_switch_server.setOnClickListener {
            context.redirectNoParam(ChooseWebServiceActivity::class.java)
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        refreshView()
    }

    //region 删除设备Dialog
    private fun showDeleteDialog() {
        CommonDialog.Builder(context, 1)
            .setTitle(getString(R.string.text_delete_device_title))
            .setContent(getString(R.string.text_is_delete_device))
            .setLeftRightText(getString(R.string.tv_cancel), getString(R.string.txt_delete_device))
            .setRightClick { _, _ ->
                BleHandle.instance.deleteDevice()
                refreshView()
            }.create().show()
    }
    //endregion

    //region UI

    /**
     * 刷新所有View
     */
    private fun refreshView() {
        val canOperate = BleHandle.instance.isCanOperateDevice()
        view_mask_mode.visibility = if (canOperate) View.GONE else View.VISIBLE
        view_mask_single.visibility = if (canOperate) View.GONE else View.VISIBLE
        view_mask_double.visibility = if (canOperate) View.GONE else View.VISIBLE
        ct_single_double.isCanClick = canOperate
        ct_snoring_intervene.isCanClick = canOperate
        ct_left_intervene.isCanClick = canOperate
        ct_right_intervene.isCanClick = canOperate

        val isDouble = SpUtil[Const.IS_DOUBLE_MODE, true]
        refreshToggleView(isMode = true, isChecked = isDouble)
        if (!isDouble && BleHandle.instance.isSingleModel()) {
            ct_single_double.isCanClick = false
            view_mask_mode.visibility = View.VISIBLE
        }

        ct_snoring_intervene.isChecked = SpUtil[Const.IS_LEFT_INTERVENE, true]
        ct_left_intervene.isChecked = SpUtil[Const.IS_LEFT_INTERVENE, true]
        ct_right_intervene.isChecked = SpUtil[Const.IS_RIGHT_INTERVENE, true]

        val isNeedUpdate = BleHandle.instance.isNeedToUpdate()
        tv_device_state.visibility = if (isNeedUpdate) View.INVISIBLE else View.VISIBLE
        layout_update.visibility = if (isNeedUpdate) View.VISIBLE else View.GONE
        if (SpUtil[Const.DEVICE_MAC, ""].isEmpty()) {//无设备
            layout_device_info.visibility = View.GONE
            tv_device_state.text = getString(R.string.text_no_device)
            tv_device_id.text = getString(R.string.tv_empty)
            aiv_around.setImageResource(R.drawable.ic_add_device)
            tv_bt.text = getString(R.string.text_add_device)
        } else {//有设备
            layout_device_info.visibility = View.VISIBLE
            if (BleHandle.instance.isConnected()) {//设备在线
                tv_device_state.text = getString(R.string.text_online)
                if (isNeedUpdate) {//有版本更新
                    tv_new_version.text =
                        getString(R.string.text_device_new_version, BleHandle.instance.getNewVersion())
                    aiv_pillow.setImageResource(R.drawable.ic_pillow_update)
                } else {
                    aiv_pillow.setImageResource(R.drawable.ic_pillow_online)
                }
            } else {
                tv_device_state.text = getString(R.string.text_offline)
                aiv_pillow.setImageResource(R.drawable.ic_pillow_offline)
            }
            aiv_around.setImageResource(R.drawable.ic_delete_device)
            tv_bt.text = getString(R.string.txt_delete_device)
            tv_device_id.text = SpUtil[Const.DEVICE_MAC, ""]
        }
    }

    /**
     * 刷新Toggle相关View
     *
     * @param isMode    是否是单双人模式
     * @param isChecked 开/关
     */
    private fun refreshToggleView(isMode: Boolean = false, isChecked: Boolean, isLeft: Boolean = false) {
        if (isMode) {
            SpUtil.put(Const.IS_DOUBLE_MODE, isChecked)
            ct_single_double.isChecked = isChecked
            tv_mode_title.setText(if (isChecked) R.string.txt_setting_double_model else R.string.txt_setting_single_model)
            tv_mode_tip.setText(if (isChecked) R.string.txt_setting_double_model_tip else R.string.txt_setting_single_model_tip)
            layout_single_intervene.visibility = if (isChecked) View.GONE else View.VISIBLE
            ct_snoring_intervene.visibility = if (isChecked) View.GONE else View.VISIBLE
            layout_double_intervene.visibility = if (isChecked) View.VISIBLE else View.GONE
        } else {
            if (isLeft) {
                ct_left_intervene.isChecked = isChecked
                ct_snoring_intervene.isChecked = isChecked
                SpUtil.put(Const.IS_LEFT_INTERVENE, isChecked)
            } else {
                ct_right_intervene.isChecked = isChecked
            }
        }
    }

    //endregion

    //region Toggle Listener

    private val checkListener = CustomToggle.OnCheckedChangeListener { toggle, isChecked, isCanClick ->
        if (!isCanClick) {
            if (SpUtil[Const.DEVICE_MAC, ""].isEmpty()) {
                context.showToast(R.string.text_tip_snore_toggle)
            } else {
                if (BleHandle.instance.isSingleModel()) {
                    context.showToast(R.string.txt_single_mode_tip)
                } else {
                    context.showToast(R.string.tip_device_offline)
                }
            }
        } else {
            when (toggle.id) {
                R.id.ct_single_double -> BleHandle.instance.sendModelOperate(isChecked)
                R.id.ct_snoring_intervene -> BleHandle.instance.sendInterveneOperate(true, isChecked)
                R.id.ct_left_intervene -> BleHandle.instance.sendInterveneOperate(true, isChecked)
                R.id.ct_right_intervene -> BleHandle.instance.sendInterveneOperate(false, isChecked)
            }
        }
    }

    //endregion

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventReceiver(event: OneEvent) {
        when (event.type) {
            Const.WRITE_CALLBACK -> if (event.getIntValue() != Const.OK_RESULT) showToast(getString(R.string.txt_write_data_fail))
            Const.LEFT_INTERVENE -> refreshToggleView(isChecked = event.getIntValue() == 1, isLeft = true)
            Const.RIGHT_INTERVENE -> refreshToggleView(isChecked = event.getIntValue() == 1, isLeft = false)
            Const.USER_MODE -> refreshToggleView(true, event.getIntValue() == 2)
            Const.DISCONNECT_DEVICE -> refreshView()
        }
    }

}